import express, { Request, Response } from 'express';
import { Category } from '../model';

const router = express.Router();

router.get('/', async (req: Request, res: Response) => {
    const { current = 1, pageSize = 10, name, level } = req.query;
    const data = await Category.find({
        ...(name && { name }) as any,
        ...(level && { level }) as any
    })
        .skip((Number(current) - 1) * Number(pageSize))  // 跳过第current * pageSize 条数据
        .populate('parent')
        .limit(Number(pageSize)); // 取出后面的 pageSize 条数据
    const total = await Category.countDocuments({
        ...(name && { name }) as any,
        ...(level && { level }) as any
    });
    return res.status(200).json({ success: true, data, total });
})

router.post('/', async (req: Request, res: Response) => {
    const { name } = req.body;
    const oldCategory = await Category.findOne({ name })
    if (oldCategory) {
        return res.status(500).json({ messae: '该分类已经存在！' })
    } else {
        const categoryModel = new Category({ ...req.body });
        categoryModel.save();
        return res.json({ success: true, code: 200 });
    }
})

router.put('/:id', async (req: Request, res: Response) => {
    const { id } = req.body;
    const body = req.body;
    await Category.findByIdAndUpdate({ _id: id }, body);
    return res.status(200).json({ success: true });
})

router.delete('/:id', async (req: Request, res: Response) => {
    const { id } = req.params;
    await Category.findByIdAndDelete(id);
    return res.status(200).json({ success: true });
})

router.get('/:id', async (req: Request, res: Response) => {
    const { id } = req.params;
    const categoryData = await Category.findById(id);
    if (categoryData) {
        return res.status(200).json({ success: true, data: categoryData });
    } else {
        return res.status(500).json({ success: false })
    }
});

export default router;